<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Web聊天室</title>
    <link rel="stylesheet" href="../css/common.css">
    <link rel="stylesheet" href="../css/message.css">
    <link href="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.staticfile.org/twitter-bootstrap/5.1.1/js/bootstrap.bundle.min.js"></script>
    <link rel="shortcut icon" href="../img/favicon.ico" type="image/x-icon">
    <link rel="icon" href="../img/favicon.ico" type="image/x-icon">
</head>
<body>
    <div id="app" v-cloak>
        <nav id="nav" class="navbar navbar-expand-sm bg-dark navbar-dark">
            <div class="container-fluid">
                <span style="color: aliceblue">欢迎您！{{ currentUser.nickname }}</span>
                <button class="btn btn-primary" type="button" onclick="{location.href='../logout'}">注销</button>
            </div>
        </nav>
        <div id="container">
            <div id="channel-list">
                <div :class="c.id==currentGroup.id ? 'channel-row-checked' : 'channel-row-unchecked'" v-for="c in groups" :key="c.id" @click="changeGroup(c)">
                    <span class="channel-item"> {{ c.name }} </span>
                    <span v-if="c.unreadCount" class="unread">{{c.unreadCount}}</span>
                </div>
            </div>
            <div id="dialog">
                <div id="dialog-history">
                    <div class="dialog-row" v-for="m in currentGroup.historyMessages" :key="m.id">
                        <div class="dialog-date">{{ m.sendTime }}</div>
                        <div class="dialog-user">{{ m.userNickname }}</div>
                        <div :class="m.userId==currentUser.id ? 'dialog-current-content' : 'dialog-other-content'">{{ m.content }}</div>
                    </div>
                </div>
                <textarea id="dialog-content" v-model="currentGroup.inputMessageContent" @keyup="checkIfSend($event)"></textarea>
                <div id="dialog-send">
                    <button @click="sendMessage()">发送（s）</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="../js/util.js"></script>
<script src="../js/vue.js"></script>
<script>
    let app = new Vue({
        el: "#app",
        data: {
            websocket:null,
            //当前登录的用户
            currentUser:{
                nickname: "",
                head:"",
            },
            groups:[
                {
                    id:"1",
                    name:"数学",
                    historyMessages:[],
                    inputMessageContent:"",
                    unreadCount: 0,

                },
                {
                    id:"2",
                    name:"语文",
                    historyMessages: [],
                    inputMessageContent: "",
                    unreadCount: 0,

                },
            ],
            currentGroup:{
                id:"1",
                name:"数学",
                historyMessages:[],
                inputMessageContent:"",
                unreadCount: 0,
            },
        },
        methods: {
            //点击切换群组
            changeGroup: function(group){
                if(group.id != app.currentGroup.id){
                    app.currentGroup = group;
                }
                //切换频道时候，滚动到最后，未读消息设置为0
                app.scrollHistory();
            },

            //从服务端获取群组列表，再设置到vue的变量中，页面就可以跟着变
            getGroup: function(){
                ajax({
                    method:"get",
                    url:"../groupList",
                    callback:function(status, responseText){
                        // console.log(responseText);//查看一下响应正文的数据是否符合业务的，可以抓包（建议）
                        if(status != 200){
                            alert("出错了，响应状态码："+status);
                            return;
                        }
                        let body = JSON.parse(responseText);//响应正文
                        app.currentUser = body.user;
                        for(let i = 0;i < body.groups.length;i++){
                            body.groups[i].historyMessages = [];
                            body.groups[i].inputMessageContent = "";
                            body.groups[i].unreadCount = 0;
                            if( i==0 ){
                                app.currentGroup = body.groups[0];
                            }
                        }
                        //返回到页面上，动态更新
                        app.groups = body.groups;
                        //初始化websocket：还需要接受消息（定义消息接受函数）
                        app.initWebsocket();
                    }
                });
            },
            initWebsocket: function (){
                //先创建一个websocket对象，用来建立连接，客户端收发数据
                //url格式————协议名://ip:port/contextPath/资源路径
                //contextPath是部署的项目名/项目路径，websocket协议名ws
                //动态获取地址
                let protocal = location.protocol;
                let url = location.href;
                url = url.substring((protocal+"//").length,url.indexOf("/views/message.html"));
                let ws = new WebSocket("ws://"+url+"/message");
                // let ws = new WebSocket("ws://localhost:8080/chatroom/message");
                //为websocket对象绑定事件（事件发生的时候，由浏览器自动调用事件函数）
                //建立连接的事件: e就是事件对象
                ws.onopen = function(e){
                    console.log("客户端建立连接")
                }
                //关闭连接的事件：关闭可能是先由服务端关闭，或者先由客户端关闭
                ws.onclose = function(e){
                    let reason = e.reason;
                    console.log("close:"+reason);
                    if(reason){
                        alert(reason);
                    }
                }
                //发生错误时的事件
                ws.onerror = function(e){
                    console.log("websocket出错了")
                }

                //接收到消息时的事件
                ws.onmessage = function(e){//服务端推送消息给客户端时，执行这个函数
                    console.log(e.data)//通过事件对象.data就可以获取到服务端推送的消息（可以是二进制数据，或字符串）
                    //遍历群组列表，如果群组id和获取到得消息中的groupId相同
                    let m = JSON.parse(e.data);
                    for(let group of app.groups){
                        if(group.id == m.groupId){
                            group.historyMessages.push(m);
                            if(m.groupId == app.currentGroup.id){
                                app.scrollHistory();
                            }else{
                                group.unreadCount++;
                            }
                        }
                    }
                }

                //刷新/关闭页面
                window.onbeforeunload = function (e){
                    //主动关闭websocket连接
                    ws.close();
                }
                app.websocket = ws;
            },

            //接收到新消息，滚动到消息位置
            scrollHistory:function(){
                app.$nextTick(function(){
                    let history =  document.querySelector("#dialog-history");
                    history.scrollTop = history.scrollHeight;
                });
                app.currentGroup.unreadCount = 0;
            },
            //绑定当前频道输入框的键盘弹起事件：检查是否为ctrl+enter来发送消息
            checkIfSend: function (e){
                if(e.keyCode == 13 && e.ctrlKey){
                    app.sendMessage();
                }
            },

            sendMessage: function(){
                let content = app.currentGroup.inputMessageContent;
                //输入框不为空，才可以法消息
                if(content){
                    //需要使用initwebsocket\
                    //后台需要插入数据库一条客户端发送的消息(user_id...,group_id,content)
                    //注意：后端是将json字符串反序列化为message对象（驼峰式）
                    app.websocket.send(JSON.stringify({
                        groupId: app.currentGroup.id,
                        content:content,
                    }));
                    app.currentGroup.inputMessageContent="";
                }
            }
        },
    });
    app.getGroup();
</script>
</html>